define(['view','model/packages'], function(View, Packages) {
  return View.extend({

    events: {
      'input #searchInput': 'onSearch',
      'click #previous': 'prePage',
      'click #next': 'nextPage',
      'click #detail': 'showDetail',
      'click #createPackage': 'createPackage'
    },

    pageSize: 10,

    currentPage: 0,

    packages: new Packages(),

    onShow: function() {
      var _this = this;
      // this.loading = new Loading().show();
      this.packages.on('sync', this.onSearchDone, this);
      this.packages.fetch();
    },

    onSearch: function(e) {
      var value = $(e.currentTarget).val();
      var models = _.filter(this.packages.models, function(model) {
        return model.get('name').toLowerCase().indexOf(value.toLowerCase()) != -1;
      });
      this.refreshResult(models);
      this.searchResult = models;
    },

    onSearchDone: function(collection, response) {
      // this.loading.hide();
      this.searchResult = collection.models;
      this.refreshResult(collection.models);
    },

    refreshResult: function(models) {
      var start = this.currentPage * this.pageSize;
      var end = this.currentPage * this.pageSize + this.pageSize;
      var data = models.slice(start, end);
      var html = this.$('#resultTmpl').html();
      tmpl = _.template(html);
      this.$("#results").html(tmpl({'packages': data}));
    },

    prePage: function() {
      this.currentPage = this.currentPage - 1 <= 0 ? 0 : --this.currentPage;
      this.refreshResult(this.searchResult);
    },

    nextPage: function() {
      this.currentPage + 1 < (this.searchResult.length / this.pageSize) && this.currentPage++;
      this.refreshResult(this.searchResult);
    },

    showDetail: function(event) {
      _this = this;
      var id = $(event.currentTarget).data('id');
      var pack = _.find(this.searchResult, function(pack) {
        return pack.get("_id") == id;
      });
      Pure.loadView('detail', null, function(view) {
        view.render(function() {
          view.init(pack.toJSON());
          view.onShow();
        });
        view.on('comment-post', _this.updatePackage, _this)
        $('[pure-content]').append(view.$el);
      })
    },

    updatePackage: function(pack) {
      console.log(this.packages.set(pack));
    },

    createPackage: function() {
      var _this = this;
      Pure.loadView('create-package', null, function(view) {
        view.render(function() {
          view.onShow();
        });
        view.on('create', function() {
          _this.packages.fetch();
        }, _this);
        $('[pure-content]').append(view.$el);
      })
    },

  });
});